package com.rpcdemo.client;

import com.alibaba.fastjson.JSON;
import com.rpcdemo.constant.SysConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

/**
 * create by yongli on 2021-12-26 08:07
 * <p>
 * 访问清求时的认证信息
 */
@Component
public class CnBlogClientInterceptor implements RequestInterceptor {

    private static final String AUTHORIZATION_HEADER = "Authorization";

    private static final String BEARER_TOKEN_TYPE = "Bearer";

    @Override
    public void apply(RequestTemplate template) {

        System.out.println("this will add some header information");
        System.out.println(JSON.toJSONString(template.requestBody()));
        System.out.println("url 可以进行分发");
        System.out.println(JSON.toJSONString(template.url()));
        System.out.println(JSON.toJSONString(template));
        System.out.println(template);

        // 安全校验相关，Authorization, Bearer
        // 去掉登录。
        // 透传前端请求头到后续请求中
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (servletRequestAttributes != null) {
            String app = servletRequestAttributes.getRequest().getHeader(SysConstant.PARAM_NAME_CURRENT_APP);

            // 可在此处走不同的分支
            System.out.println("主机");
            System.out.println(servletRequestAttributes.getRequest().getRemoteHost());
            System.out.println(servletRequestAttributes.getRequest().getRequestURL().toString());
            System.out.println(servletRequestAttributes.getRequest().getRemoteAddr());

            HttpServletResponse response = servletRequestAttributes.getResponse();

            String tenant = servletRequestAttributes.getRequest()
                    .getHeader(SysConstant.PARAM_NAME_CURRENT_TENANT);
            String appToken = servletRequestAttributes.getRequest()
                    .getHeader(SysConstant.PARAM_NAME_APP_TOKEN);
            String reqSource = servletRequestAttributes.getRequest()
                    .getHeader(SysConstant.PARAM_NAME_REQ_SOURCE);

            template.header(SysConstant.PARAM_NAME_APP_TOKEN, app);
            template.header(SysConstant.PARAM_NAME_APP_TOKEN, tenant);
            template.header(SysConstant.PARAM_NAME_APP_TOKEN, appToken);
            template.header(SysConstant.PARAM_NAME_APP_TOKEN, reqSource);
        }

    }
}
